<?php

namespace app\controllers;

use app\models\Class1;
use app\models\Class2;
use app\models\ReadContent;
use app\models\SpeakContent;
use app\models\SpeakPerson;
use app\models\TbUser;
use app\models\User;
use app\models\WritePerson;
use yii\db\Query;
use yii\filters\AccessControl;
use yii\helpers\Url;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\web\Cookie;


class SiteController extends Controller
{
    public $layout='main';
    /**
     * @inheritdoc
     */

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * 获取最新课程的url
     */
    private function getCourseUrl()
    {
        $time=date('Y-m-d');
        $db=\Yii::$app->get('passportdb');
        $on='`tb_course`.`course_id`=`tb_courseissue`.`course_id`';
        $where=['tb_course.status'=>0];
        $res=[];
        for($i=1;$i<5;$i++)
        {
            $query=new Query();
            $andWhere=['and',
                'tb_course.teachingForm=1',
                "tb_course.channel=1",
                "tb_course.type=$i",
                "tb_courseissue.startDate >='$time'"];
            $item=$query
                ->select(['tb_course.course_id','tb_course.name'])
                ->from(['tb_course'])
                ->join('INNER JOIN',['tb_courseissue'],$on)
                ->where($where)
                ->andWhere($andWhere)
                ->orderBy(['tb_courseissue.startDate'=>SORT_ASC])
                ->limit(1)
                ->one($db);
            array_push($res,$item);
        }
        return $res;

    }
    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        $request=\Yii::$app->request;
        $class1_id=$request->get('id');
        $seesion=\Yii::$app->session;
        $seesion->open();
        $session['class1_id']=$class1_id;
        $class_reading_id=Class1::find()->where(['name'=>'reading'])->one();
        $class_speaking_id=Class1::find()->where(['name' => 'speaking'])->one();
        $class_writing_id=Class1::find()->where(['name' => 'writing'])->one();
        $class_1_tpo = ReadContent::find()->where(['class1_id' => $class_reading_id['id']])->all();
        $class_1_name = Class1::find()->where(['id' => $class_reading_id['id']])->all();
        $class_2_name = Class2::find()->where(['class1_id' => $class_reading_id['id']])->all();
        $speakingclass2_name = Class2::find()->where(['class1_id' => $class_speaking_id['id']])->all();
        $speaking_hear_number = SpeakContent::find()->select('hear_number')->orderBy('hear_number')->
        groupBy('hear_number')->where(['class1_id' => $class_speaking_id['id']])->all();
        $speakingclass1_name = Class1::find()->where(['id' => $class_speaking_id['id']])->all();
        $write_class2_name=Class2::find()->where(['class1_id'=>$class_writing_id['id']])->all();
        $write_class1_name=Class1::find()->where(['id'=>$class_writing_id['id']])->all();
        return $this->render('index',
            ['speakingclass2_name' => $speakingclass2_name,
             'speaking_hear_number' => $speaking_hear_number,
             'speakingclass1_name' => $speakingclass1_name,
             'class_1_tpo' => $class_1_tpo,
             'class_1_name' => $class_1_name,
             'class_2_name' => $class_2_name,
                'write_class1_name'=>$write_class1_name,
                'write_class2_name'=>$write_class2_name,
                'res_url'=>$this->getCourseUrl()
            ]
        );
    }

    /**
     * Login action.
     *
     * @return string
     */
    public function actionLogin()
    {
        $this->layout='main-nofoot';
        $request= \Yii::$app->request;
        $islogin=$request->get('islogin');
        if(isset($islogin))
        {
            setcookie('dianke_user_id',$islogin);
            $this->redirect('?r=site/dologin&islogin='.$islogin);
        }
        return $this->render('login');
    }
    public function actionDologin()
    {
        $request= \Yii::$app->request;
        if($request->isGet)
        {
            $islogin=$request->get('islogin');
            if(!isset($islogin))
                die();
            $cookie=$this->passport_decrypt($islogin);
            $len=strlen($cookie);
            $userid=substr($cookie,13,$len-24);
            $tb_user=TbUser::findOne($userid);
            $session = \Yii::$app->session;
            $session->open();
            $session['user_id']=$tb_user['user_id'];
            $session['name']=$tb_user['name'];
            $session['email']=$tb_user['email'];
            $session['photo']=$tb_user['photo'];
            $session['source']=$tb_user['source'];
            $session['openid']=$tb_user['openid'];
            $session['unionid']=$tb_user['unionid'];
            $user=User::findOne($session['user_id']);
            if(!isset($user))
            {
                $user = new User();
            }
            $user->user_id = $session['user_id'];
            $user->name = $session['name']!=""?$session['name']:"萌萌";
            $user->photo = $session['photo']!=""?$session['photo']:"#";
            $user->source = $session['source']!=""?$session['source']:Url::to('@web/images/timg.jpg');
            $user->openid = $session['openid']!=""?$session['openid']:"1";
            $user->email = $session['email']!=""?$session['email']:"none@dianketai.com";
            $user->unionid = $session['unionid']!=""?$session['unionid']:"1";
            $user->save();
            $this->goBack();


        }
        return $this->redirect('?r=site/index');
    }

    /**
     * Logout action.
     *
     * @return string
     */
    public function actionLogout()
    {
        $session = \Yii::$app->session;
        setcookie('dianke_user_id','');
        $session->removeAll();
        return $this->redirect('?r=site/index');

    }
    /**
     * Displays about page.
     *
     * @return string
     */
    public function actionError()
    {
        return $this->render('error');
    }

    public function actionReading()
    {
        return $this->render('reading');
    }

    private function passport_decrypt($str)
    { // 解密函数
        $key = "Dianketai6666";
        $str = $this->passport_key ( base64_decode ( $str ), $key );
        $tmp = '';
        for($i = 0; $i < strlen ( $str ); $i ++) {
            $md5 = $str [$i];
            $tmp .= $str [++ $i] ^ $md5;
        }
        return $tmp;
    }
    private function passport_key($str, $encrypt_key)
    { // 辅助加减密函数
        $encrypt_key = md5 ( $encrypt_key );
        $ctr = 0;
        $tmp = '';
        for($i = 0; $i < strlen ( $str ); $i ++) {
            $ctr = $ctr == strlen ( $encrypt_key ) ? 0 : $ctr;
            $tmp .= $str [$i] ^ $encrypt_key [$ctr ++];
        }
        return $tmp;
    }
}
